#include "ntc.h"
#include "systimer.h"
#define ADC_FILTER_NUM  10

static uint16_t adcVal[ADC_FILTER_NUM];

static void ntc_adc_init(void)
{
    /* 时钟使能 */
    rcu_periph_clock_enable(RCU_GPIOB);
    rcu_periph_clock_enable(RCU_AF);
    rcu_periph_clock_enable(RCU_ADC0);
    rcu_adc_clock_config(RCU_CKADC_CKAPB2_DIV8);

    gpio_init(GPIOB, GPIO_MODE_AIN, GPIO_OSPEED_2MHZ, GPIO_PIN_0);

    adc_mode_config(ADC_MODE_FREE);
    adc_special_function_config(ADC0, ADC_CONTINUOUS_MODE, ENABLE);
    adc_data_alignment_config(ADC0, ADC_DATAALIGN_RIGHT);
    adc_channel_length_config(ADC0, ADC_REGULAR_CHANNEL, 1);
    adc_regular_channel_config(ADC0, 0, ADC_CHANNEL_8, ADC_SAMPLETIME_239POINT5);
    adc_external_trigger_source_config(ADC0, ADC_REGULAR_CHANNEL, ADC0_1_2_EXTTRIG_REGULAR_NONE);
    adc_external_trigger_config(ADC0, ADC_REGULAR_CHANNEL, ENABLE);
    adc_dma_mode_enable(ADC0);
    adc_enable(ADC0);
    delay_ms(1);
    adc_calibration_enable(ADC0);
    adc_software_trigger_enable(ADC0, ADC_REGULAR_CHANNEL);
}

static void ntc_dma_init(void)
{
    rcu_periph_clock_enable(RCU_DMA0);

    dma_parameter_struct dmaInitStruct;
    dmaInitStruct.periph_addr = (uint32_t)(&ADC_RDATA(ADC0));
    dmaInitStruct.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
    dmaInitStruct.memory_addr = (uint32_t)(&adcVal);
    dmaInitStruct.memory_width = DMA_MEMORY_WIDTH_16BIT;
    dmaInitStruct.number = ADC_FILTER_NUM;
    dmaInitStruct.priority = DMA_PRIORITY_LOW;
    dmaInitStruct.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dmaInitStruct.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dmaInitStruct.direction = DMA_PERIPHERAL_TO_MEMORY;
    dma_init(DMA0, DMA_CH0, &dmaInitStruct);
    dma_circulation_enable(DMA0, DMA_CH0);
    dma_channel_enable(DMA0, DMA_CH0);
}

uint16_t ntc_get_adVal(void)
{
    uint32_t valSum = 0;
    for(uint8_t i = 0; i < ADC_FILTER_NUM; i++)
    {
        valSum += adcVal[i];
    }
    return (valSum / ADC_FILTER_NUM);
}

void ntc_init(void)
{
    ntc_dma_init();
    ntc_adc_init();
}

// void ntc_self_test(void)
// {
//     printf("ntcVal = %d\n", ntc_get_adVal());
// }
